<template>
	<view class="container">
		<!-- Header -->
		<view class="header">
			<view class="title">创建访客预约</view>
		</view>

		<!-- Info Tip -->
		<view class="info-tip">
			<view class="tip-icon">ℹ</view>
			<text class="tip-text">访客预约请填写以下信息：</text>
		</view>

		<!-- Form -->
		<view class="form-container">
			<!-- 访客信息 -->
			<view class="form-section">
				<view class="section-title">访客信息</view>
				<view class="form-item">
					<text class="label">您的姓名 <text class="required">*必填</text></text>
					<input
						
						type="text"
						confirm-type="done"
						@input="inputHandler"
						placeholder="李珍珍"
						v-model="formData.visitor_name"
					/>
				</view>
				<view class="form-item">
					<text class="label">手机号 <text class="required">*必填</text></text>
					<input
						
						type="number"
						maxlength="11"
						confirm-type="done"
						@input="phoneInputHandler"
						placeholder="15555555555"
						v-model="formData.visitor_phone"
					/>
				</view>
				<view class="form-item">
					<text class="label">性别</text>
					<picker :range="genderOptions" @change="genderChange">
						<view class="picker">
							<text>{{ formData.visitor_gender ? (formData.visitor_gender === 'M' ? '男' : '女') : '男' }}</text>
							<text class="picker-arrow">></text>
						</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="label">身份证号 <text class="optional">(选填)</text></text>
					<input
						class="form-input"
						type="text"
						maxlength="18"
						confirm-type="done"
						@input="idCardInputHandler"
						placeholder="请填写"
						v-model="formData.visitor_id_card"
					/>
				</view>
				<view class="form-item">
					<text class="label">邮箱 <text class="optional">(选填)</text></text>
					<input
						class="form-input"
						type="text"
						confirm-type="done"
						@input="inputHandler"
						placeholder="请填写"
						v-model="formData.visitor_email"
					/>
				</view>
				<view class="form-item">
					<text class="label">所属公司 <text class="optional">(选填)</text></text>
					<input
						class="form-input"
						type="text"
						confirm-type="done"
						@input="inputHandler"
						placeholder="请填写"
						v-model="formData.visitor_company"
					/>
				</view>
			</view>
			
			<!-- 预约信息 -->
			<view class="form-section">
				<view class="section-title">预约信息</view>
				<view class="form-item">
					<text class="label">被访企业</text>
					<picker
						:range="companyList"
						range-key="company_name"
						@change="companyChange"
					>
						<view class="picker">
							<text>{{ selectedCompany ? selectedCompany.company_name : '济南方方信息技术有限公司' }}</text>
							<text class="picker-arrow">></text>
						</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="label">来访目的 <text class="required">*必填</text></text>
					<textarea
						class="form-textarea"
						placeholder="对公司的项目进行一些考察，看能不能投资该公司。"
						v-model="formData.visit_purpose"
						maxlength="200"
						@input="textareaInputHandler"
					></textarea>
				</view>
				<view class="form-item">
					<text class="label">预约时间 <text class="required">*请选择</text></text>
					<view class="date-time-picker">
						<view class="picker" @click="showCalendar">
							<text>{{ formData.visit_date || '2025-02-15' }}</text>
							<text class="picker-arrow">></text>
						</view>
						<picker
							mode="time"
							:value="formData.visit_time"
							@change="timeChange"
						>
							<view class="picker">
								<text>{{ formData.visit_time || '10:30' }}</text>
								<text class="picker-arrow">></text>
							</view>
						</picker>
					</view>
				</view>

				<!-- 日历弹窗 -->
				<view v-if="calendarVisible" class="calendar-overlay" @click="hideCalendar">
					<view class="calendar-popup" @click.stop>
						<view class="calendar-header">
							<text class="calendar-title">选择日期</text>
							<text class="calendar-close" @click="hideCalendar">×</text>
						</view>
						<view class="calendar-content">
							<view class="calendar-nav">
								<text class="nav-btn" @click="prevMonth">‹</text>
								<text class="current-month">{{ currentYear }}年{{ currentMonth }}月</text>
								<text class="nav-btn" @click="nextMonth">›</text>
							</view>
							<view class="calendar-weekdays">
								<text class="weekday" v-for="day in weekdays" :key="day">{{ day }}</text>
							</view>
							<view class="calendar-days">
								<text
									class="calendar-day"
									:class="getDayClass(day)"
									v-for="day in calendarDays"
									:key="day.key"
									@click="selectDate(day)"
								>
									{{ day.date }}
								</text>
							</view>
						</view>
					</view>
				</view>
				<view class="form-item">
					<text class="label">陪同人信息 <text class="optional">(选填)</text></text>
					<input
						class="form-input"
						type="text"
						confirm-type="done"
						@input="inputHandler"
						placeholder="这是一条信息"
						v-model="formData.accompanier_info"
					/>
				</view>
			</view>
		</view>
		
		<!-- Submit Button -->
		<view class="submit-btn" @click="submitForm">提交预约</view>
	</view>
</template>

<script>
import { visitorAppointmentAPI } from '@/api/services.js';
import { request } from '@/api/request.js';

export default {
	data() {
		return {
			formData: {
				visitor_name: '',
				visitor_phone: '',
				visitor_gender: '',
				visitor_id_card: '',
				visitor_email: '',
				visitor_company: '',
				visit_purpose: '',
				visit_date: '',
				visit_time: '',
				visited_company_id: '',
				accompanier_info: ''
			},
			genderOptions: ['男', '女'],
			companyList: [],
			selectedCompany: null,
			loading: false,
			userId: null,
			// 日历相关数据
			calendarVisible: false,
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth() + 1,
			weekdays: ['日', '一', '二', '三', '四', '五', '六'],
			calendarDays: []
		};
	},
	onLoad() {
		this.getCompanyList();
		this.getUserInfo();
		this.generateCalendar();
	},
	methods: {
		// 获取用户信息
		getUserInfo() {
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo && userInfo.userId) {
				this.userId = userInfo.userId;
				console.log('当前用户ID:', this.userId);
			} else {
				console.error('用户ID未找到');
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
			}
		},
		// 获取企业列表
		getCompanyList() {
			// 使用API获取真实企业数据
			visitorAppointmentAPI.getCompanyList()
				.then(res => {
					if (res.code === 200 && res.list && res.list.length > 0) {
						this.companyList = res.list;
						console.log('获取企业列表成功:', this.companyList);
						
						// 默认选择第一个公司
						this.selectedCompany = this.companyList[0];
						this.formData.visited_company_id = Number(this.selectedCompany.company_id);
					} else {
						console.error('获取企业列表返回数据格式不正确:', res);
						this.useDefaultCompanyList();
					}
				})
				.catch(err => {
					console.error('获取企业列表失败:', err);
					this.useDefaultCompanyList();
				});
		},
		
		// 使用默认企业列表（当API调用失败时的后备方案）
		useDefaultCompanyList() {
			console.log('使用默认企业数据');
			this.companyList = [
				{ company_id: 1, company_name: '盛美集团' },
				{ company_id: 2, company_name: '慧联科技' },
				{ company_id: 3, company_name: '东方电子' },
				{ company_id: 4, company_name: '锐创科技' },
				{ company_id: 5, company_name: '智能科技有限公司' },
				{ company_id: 6, company_name: '未来信息技术' }
			];
			
			// 默认选择第一个公司
			this.selectedCompany = this.companyList[0];
			this.formData.visited_company_id = Number(this.selectedCompany.company_id);
		},
		
		// 性别选择
		genderChange(e) {
			const index = e.detail.value;
			this.formData.visitor_gender = index === '0' ? 'M' : 'F';
		},
		
		// 显示日历弹窗
		showCalendar() {
			this.calendarVisible = true;
		},

		// 隐藏日历弹窗
		hideCalendar() {
			this.calendarVisible = false;
		},

		// 生成日历数据
		generateCalendar() {
			const year = this.currentYear;
			const month = this.currentMonth;

			// 获取当月第一天是星期几
			const firstDay = new Date(year, month - 1, 1).getDay();

			// 获取当月天数
			const daysInMonth = new Date(year, month, 0).getDate();

			// 获取上个月天数
			const daysInPrevMonth = new Date(year, month - 1, 0).getDate();

			const calendarDays = [];

			// 添加上个月的日期
			for (let i = firstDay - 1; i >= 0; i--) {
				calendarDays.push({
					date: daysInPrevMonth - i,
					isCurrentMonth: false,
					isPrevMonth: true,
					key: `prev-${daysInPrevMonth - i}`
				});
			}

			// 添加当月的日期
			const today = new Date();
			const currentDate = today.getDate();
			const currentMonthYear = today.getFullYear() === year && today.getMonth() + 1 === month;

			for (let i = 1; i <= daysInMonth; i++) {
				calendarDays.push({
					date: i,
					isCurrentMonth: true,
					isToday: currentMonthYear && i === currentDate,
					key: `current-${i}`
				});
			}

			// 添加下个月的日期
			const totalDaysNeeded = 42; // 6行 x 7列
			const remainingDays = totalDaysNeeded - calendarDays.length;

			for (let i = 1; i <= remainingDays; i++) {
				calendarDays.push({
					date: i,
					isCurrentMonth: false,
					isNextMonth: true,
					key: `next-${i}`
				});
			}

			this.calendarDays = calendarDays;
		},

		// 上个月
		prevMonth() {
			if (this.currentMonth === 1) {
				this.currentYear--;
				this.currentMonth = 12;
			} else {
				this.currentMonth--;
			}
			this.generateCalendar();
		},

		// 下个月
		nextMonth() {
			if (this.currentMonth === 12) {
				this.currentYear++;
				this.currentMonth = 1;
			} else {
				this.currentMonth++;
			}
			this.generateCalendar();
		},

		// 获取日期样式类
		getDayClass(day) {
			const classes = [];

			if (!day.isCurrentMonth) {
				classes.push('other-month');
			}

			if (day.isToday) {
				classes.push('today');
			}

			// 检查是否是选中的日期
			if (this.formData.visit_date) {
				const selectedDate = new Date(this.formData.visit_date);
				const dayDate = new Date(this.currentYear, this.currentMonth - 1, day.date);

				if (day.isCurrentMonth &&
					selectedDate.getFullYear() === this.currentYear &&
					selectedDate.getMonth() + 1 === this.currentMonth &&
					selectedDate.getDate() === day.date) {
					classes.push('selected');
				}
			}

			return classes;
		},

		// 选择日期
		selectDate(day) {
			if (!day.isCurrentMonth) {
				// 如果选择的是上个月或下个月的日期，切换到对应月份
				if (day.isPrevMonth) {
					this.prevMonth();
				} else if (day.isNextMonth) {
					this.nextMonth();
				}
				return;
			}

			// 格式化日期为YYYY-MM-DD
			const month = this.currentMonth.toString().padStart(2, '0');
			const date = day.date.toString().padStart(2, '0');
			this.formData.visit_date = `${this.currentYear}-${month}-${date}`;

			// 隐藏日历
			this.calendarVisible = false;
		},

		// 时间选择
		timeChange(e) {
			this.formData.visit_time = e.detail.value;
		},
		
		// 企业选择
		companyChange(e) {
			const index = e.detail.value;
			this.selectedCompany = this.companyList[index];
			// 确保设置visited_company_id为数字类型，与Django API一致
			this.formData.visited_company_id = Number(this.selectedCompany.company_id);
			console.log('已选择企业:', this.selectedCompany.company_name, '企业ID:', this.formData.visited_company_id);
		},
		
		// 表单验证
		validateForm() {
			// 访客姓名
			if (!this.formData.visitor_name.trim()) {
				uni.showToast({
					title: '请输入访客姓名',
					icon: 'none'
				});
				return false;
			}
			
			// 访客手机号
			if (!this.formData.visitor_phone.trim()) {
				uni.showToast({
					title: '请输入访客手机号',
					icon: 'none'
				});
				return false;
			}
			
			// 手机号格式验证
			if (!/^1\d{10}$/.test(this.formData.visitor_phone)) {
				uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				});
				return false;
			}
			
			// 身份证号格式验证（如果填写了才验证）
			if (this.formData.visitor_id_card.trim() && 
			   !/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/.test(this.formData.visitor_id_card)) {
				uni.showToast({
					title: '身份证号格式不正确',
					icon: 'none'
				});
				return false;
			}
			
			// 来访事由
			if (!this.formData.visit_purpose.trim()) {
				uni.showToast({
					title: '请输入来访事由',
					icon: 'none'
				});
				return false;
			}
			
			// 日期验证
			if (!this.formData.visit_date) {
				uni.showToast({
					title: '请选择来访日期',
					icon: 'none'
				});
				return false;
			}
			
			// 时间验证
			if (!this.formData.visit_time) {
				uni.showToast({
					title: '请选择来访时间',
					icon: 'none'
				});
				return false;
			}
			
			// 确保被访企业ID是整数
			if (!this.formData.visited_company_id) {
				this.formData.visited_company_id = 1; // 默认设置为1
			}
			
			return true;
		},
		
		// 输入处理器 - 普通文本
		inputHandler(e) {
			console.log('输入事件触发:', e.detail.value);
		},
		
		// 手机号输入处理
		phoneInputHandler(e) {
			console.log('手机号输入:', e.detail.value);
			// 确保只能输入数字
			this.formData.visitor_phone = e.detail.value.replace(/\D/g, '');
		},
		
		// 身份证号输入处理
		idCardInputHandler(e) {
			console.log('身份证号输入:', e.detail.value);
			// 允许数字和末尾的X/x
			const value = e.detail.value;
			this.formData.visitor_id_card = value.replace(/[^\dXx]/g, '');
		},
		
	// 文本域输入处理
	textareaInputHandler(e) {
		console.log('文本域输入:', e.detail.value);
	},
	
	// 创建访客
	async createVisitor() {
		const visitorData = {
			name: this.formData.visitor_name,
			phone: this.formData.visitor_phone,
			gender: this.formData.visitor_gender || 'M'
		};
		
		// 只有当身份证号不为空时才添加
		if (this.formData.visitor_id_card && this.formData.visitor_id_card.trim()) {
			visitorData.id_card = this.formData.visitor_id_card.trim();
		}
		
		try {
			const response = await request({
				url: '/api/users/visitors/',
				method: 'POST',
				data: visitorData
			});
			
			if (response.code === 201) {
				return response.data.visitor_id;
			} else {
				throw new Error(response.message || '创建访客失败');
			}
		} catch (error) {
			console.error('创建访客失败:', error);
			throw error;
		}
	},
	
	// 提交表单
	async submitForm() {
		if (!this.validateForm()) return;
		
		// 检查用户是否登录
		if (!this.userId) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			return;
		}
		
		this.loading = true;
		
		try {
			// 第一步：创建访客
			const visitorId = await this.createVisitor();
			console.log('访客创建成功，ID:', visitorId);
			
			// 第二步：创建预约
			// 合并日期和时间，并添加时区信息
			let dateTimeStr = `${this.formData.visit_date} ${this.formData.visit_time}`;
			
			// 创建日期对象
			const dateObj = new Date(dateTimeStr);
			
			// 格式化为ISO格式，包含时区信息
			const expected_visit_time = dateObj.toISOString();
			
			console.log('原始日期时间:', dateTimeStr);
			console.log('转换后带时区的日期时间:', expected_visit_time);
			
			// 构造预约提交数据
			const appointmentData = {
				visitor_id: visitorId,
				visit_purpose: this.formData.visit_purpose,
				expected_visit_time: expected_visit_time,
				// 将邮箱和公司信息合并到陪同人信息中
				accompanier_info: JSON.stringify({
					accompanier: this.formData.accompanier_info || '',
					visitor_email: this.formData.visitor_email || '',
					visitor_company: this.formData.visitor_company || ''
				}),
				// 确保被访企业ID为整数
				visited_company_id: parseInt(this.formData.visited_company_id) || 1,
				// 添加邀请人ID
				inviter_user_id: parseInt(this.userId)
			};
			
			console.log('提交的被访企业ID:', appointmentData.visited_company_id, '类型:', typeof appointmentData.visited_company_id);
			console.log('提交预约数据:', appointmentData);
			
			// 创建预约
			const res = await visitorAppointmentAPI.createAppointment(appointmentData);
			
			if (res.code === 201 || res.code === 200) {
				// 设置全局刷新标志
				uni.setStorageSync('appointmentListNeedRefresh', true);
				
				// 发送刷新事件通知列表页面
				uni.$emit('refreshAppointmentList');
				
				uni.showToast({
					title: '预约创建成功',
					icon: 'success'
				});
				
				// 使用redirectTo替代navigateBack，强制重新加载列表页面
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/appointment/list'
					});
				}, 1500);
			} else {
				uni.showToast({
					title: res.message || '预约创建失败',
					icon: 'none'
				});
			}
		} catch (err) {
			console.error('预约创建失败:', err);
			
			// 如果是连接问题，模拟成功并存储到本地
			if (err.errMsg && err.errMsg.includes('request:fail')) {
				// 存储到本地缓存
				const localAppointments = uni.getStorageSync('localAppointments') || [];
				const newAppointment = {
					visitor: {
						name: this.formData.visitor_name,
						phone: this.formData.visitor_phone,
						gender: this.formData.visitor_gender || 'M'
					},
					visit_purpose: this.formData.visit_purpose,
					expected_visit_time: `${this.formData.visit_date} ${this.formData.visit_time}`,
					accompanier_info: JSON.stringify({
						accompanier: this.formData.accompanier_info || '',
						visitor_email: this.formData.visitor_email || '',
						visitor_company: this.formData.visitor_company || ''
					}),
					visited_company_id: parseInt(this.formData.visited_company_id) || 1,
					inviter_user_id: parseInt(this.userId),
					appointment_id: 'local_' + Date.now(),
					status: 'pending',
					created_at: new Date().toISOString().replace('T', ' ').substring(0, 19)
				};
				
				localAppointments.push(newAppointment);
				uni.setStorageSync('localAppointments', localAppointments);
				
				// 设置全局刷新标志
				uni.setStorageSync('appointmentListNeedRefresh', true);
				
				// 发送刷新事件通知列表页面
				uni.$emit('refreshAppointmentList');
				
				uni.showToast({
					title: '预约已保存到本地',
					icon: 'success'
				});
				
				// 使用redirectTo替代navigateBack，强制重新加载列表页面
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/appointment/list'
					});
				}, 1500);
			} else {
				uni.showToast({
					title: err.message || '预约创建失败',
					icon: 'none'
				});
			}
		} finally {
			this.loading = false;
		}
	}
}
};
</script>

<style lang="scss">
.container {
	padding: 0;
	background-color: #F2F2F7;
	min-height: 100vh;
}

.header {
	background: linear-gradient(135deg, #6C7CE7 0%, #4A89DC 100%);
	padding: 40rpx 30rpx 30rpx;

	.title {
		font-size: 36rpx;
		font-weight: 600;
		color: #FFFFFF;
		text-align: center;
	}
}

.info-tip {
	background-color: #E3F2FD;
	margin: 20rpx;
	padding: 20rpx;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	border-left: 4rpx solid #2196F3;
}

.tip-icon {
	width: 40rpx;
	height: 40rpx;
	background-color: #2196F3;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #FFFFFF;
	font-size: 24rpx;
	font-weight: bold;
	margin-right: 16rpx;
}

.tip-text {
	font-size: 28rpx;
	color: #1976D2;
	font-weight: 500;
}

.form-container {
	margin-bottom: 40rpx;
	padding: 0 20rpx;
}

.form-section {
	background-color: #FFFFFF;
	border-radius: 20rpx;
	padding: 32rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		margin-bottom: 24rpx;
		color: #1C1C1E;
	}

	.form-item {
		margin-bottom: 32rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.label {
			display: block;
			margin-bottom: 16rpx;
			font-size: 28rpx;
			color: #1C1C1E;
			font-weight: 500;

			.required {
				color: #FF3B30;
				font-size: 24rpx;
			}

			.optional {
				color: #8E8E93;
				font-size: 24rpx;
			}
		}

		.form-input {
			width: 100%;
			padding: 24rpx;
			background-color: #F2F2F7;
			border: none;
			border-radius: 12rpx;
			font-size: 28rpx;
			box-sizing: border-box;
			color: #1C1C1E;
		}

		.form-textarea {
			width: 100%;
			height: 160rpx;
			padding: 24rpx;
			background-color: #F2F2F7;
			border: none;
			border-radius: 12rpx;
			font-size: 28rpx;
			box-sizing: border-box;
			color: #1C1C1E;
			line-height: 1.4;
		}

		.picker {
			width: 100%;
			padding: 24rpx;
			background-color: #F2F2F7;
			border-radius: 12rpx;
			font-size: 28rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #1C1C1E;
		}

		.picker-arrow {
			color: #8E8E93;
			font-size: 24rpx;
		}

		.date-time-picker {
			display: flex;
			justify-content: space-between;
			gap: 16rpx;

			.picker {
				flex: 1;
				min-width: 260rpx;
				overflow: hidden;
			}
		}
	}
}

.submit-btn {
	width: calc(100% - 40rpx);
	height: 96rpx;
	background: linear-gradient(135deg, #6C7CE7 0%, #4A89DC 100%);
	color: #FFFFFF;
	font-size: 32rpx;
	font-weight: 600;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 48rpx;
	margin: 40rpx 20rpx;
	box-shadow: 0 8rpx 24rpx rgba(108, 124, 231, 0.4);

	&:active {
		opacity: 0.9;
		transform: scale(0.98);
	}
}

/* 日历样式 */
.calendar-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.calendar-popup {
	width: 90%;
	background-color: #FFFFFF;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
}

.calendar-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #F2F2F7;
}

.calendar-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #1C1C1E;
}

.calendar-close {
	font-size: 40rpx;
	color: #8E8E93;
	padding: 10rpx;
}

.calendar-content {
	padding: 20rpx;
}

.calendar-nav {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.nav-btn {
	font-size: 36rpx;
	color: #007AFF;
	padding: 10rpx 20rpx;
}

.current-month {
	font-size: 28rpx;
	font-weight: 600;
	color: #1C1C1E;
}

.calendar-weekdays {
	display: flex;
	justify-content: space-around;
	margin-bottom: 10rpx;
}

.weekday {
	width: 14.28%;
	text-align: center;
	font-size: 24rpx;
	color: #8E8E93;
	padding: 10rpx 0;
}

.calendar-days {
	display: flex;
	flex-wrap: wrap;
}

.calendar-day {
	width: 14.28%;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #1C1C1E;
}

.calendar-day.other-month {
	color: #C7C7CC;
}

.calendar-day.today {
	color: #007AFF;
	font-weight: 600;
}

.calendar-day.selected {
	background-color: #007AFF;
	color: #FFFFFF;
	border-radius: 50%;
}
</style> 